package com.hutiao.snowhb.actions.wechat;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;

import com.hutiao.snowhb.common.MongoUtil;
import com.hutiao.snowhb.common.WeixinUtil;
import com.hutiao.snowhb.entities.SnowMM;
import com.hutiao.snowhb.entities.UserLocation;
import com.hutiao.snowhb.entities.WeixinUserInfo;
import com.hutiao.snowhb.resource.ConfigInfo;
import com.hutiao.snowhb.service.SnowMMService;
import com.hutiao.snowhb.service.UserService;
import com.hutiao.snowhb.wechat.tools.WeiXinTools;
import com.hutiao.snowhb.wechat.vo.WxRecvEventClick;
import com.hutiao.snowhb.wechat.vo.WxRecvEventSubscribe;
import com.hutiao.snowhb.wechat.vo.WxSendMsg;
import com.hutiao.snowhb.wechat.vo.WxSendNewsMsg;
import com.hutiao.snowhb.wechat.vo.WxSendTextMsg;
import com.opensymphony.xwork2.ActionSupport;

public class HandleEventMsgAction extends ActionSupport implements ServletRequestAware {

	private static final long serialVersionUID = -3485428114165386179L;

	private static Logger logger = Logger.getLogger(HandleEventMsgAction.class);

	private HttpServletRequest request;
	
	private String result;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SnowMMService mmService;

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	
	
	@Action(value="handleeventmsg",
			results = {
				@Result(name="success",type="xmlstr", params={"stringName", "result"})})
	public String execute() throws Exception {
		
		if (this.request.getAttribute("recvMsg") instanceof WxRecvEventSubscribe) {
			
			logger.info("msg type is WxRecvEventSubscribe");
			WxRecvEventSubscribe subsEvent = (WxRecvEventSubscribe) this.request.getAttribute("recvMsg");
			return this.handleEvent(subsEvent);
			
		} else if (this.request.getAttribute("recvMsg") instanceof WxRecvEventClick) {
			
			logger.info("msg type is WxRecvEventClick");
			WxRecvEventClick clickEvent = (WxRecvEventClick) this.request.getAttribute("recvMsg");
			return this.handleClickEvent(clickEvent);
			
		}
		
		return SUCCESS;
	}
	
	/**
	 * 处理关注/取消关注事件
	 * @param msg
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public String handleEvent(WxRecvEventSubscribe subsEvent) throws JDOMException, IOException {
		
		WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(subsEvent);
		
		if (subsEvent.getEvent().equals("subscribe")) {
			
			String openId = subsEvent.getFromUser();
			
			// 获取微信用户资料，并保存到本地数据库
			try {
				WeixinUserInfo wxu = WeixinUtil.getUserInfo(openId);
				this.userService.saveUser(wxu);
			} catch (Exception e) {
				logger.error("Exception", e);
			}
			
			StringBuffer buffer = new StringBuffer();  
//		    buffer.append("欢迎关注雪花湖北！雪花湖北诚挚邀请您参加9.5-9.14在武汉客厅举办的2014武汉东西湖(华润雪花)国际啤酒节暨食品节，");
//		    buffer.append("想了解更多活动信息，请<a href=\"http://static.hutiao.me/snow/huodong/pjjwh/index.html\">点击详情</a>").append("\n");
			buffer.append("欢迎关注雪花湖北！我们致力于提供有价值的内容，在这里您可以看到雪花妹“养在深闺人未识”的一面，无论是凝聚历史智慧的古建筑，还是都市人勇闯天涯的绿野青峰梦，它们或是一种文化、一种精神，或是一份美丽、一份感动，带给人勇气与力量！");
			
			sendMsg = new WxSendTextMsg(sendMsg, buffer.toString());
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
			
			if (subsEvent.getEventKey() != null && !subsEvent.getEventKey().equals("")) {
				
				// 处理扫描二维码
				
			}
		} else if (subsEvent.getEvent().equals("scan")) {
			// 处理已经是关注的用户扫描二维码时间
			
		} else if (subsEvent.getEvent().equals("unsubscribe")) {
			// 用户取消关注
			String openId = subsEvent.getFromUser();
			this.userService.unsubscribe(openId);
		}
		
		return SUCCESS;
	}
	
	
	
	/**
	 * 处理菜单点击事件
	 * @param msg
	 * @return
	 * @throws Exception 
	 */
	public String handleClickEvent(WxRecvEventClick clickEvent) throws Exception {
		WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(clickEvent);
		
		if (clickEvent.getEventKey().equals("V1001_PINPAI_CHINA")) {
			// 品牌-雪花中国
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("雪花中国", 
					"雪花啤酒品牌销量从2005年开始连续9年居中国啤酒品牌销量第一，2006年起华润雪花企业总销量连续8年蝉联中国啤酒行业销量第一桂冠。2011年华润雪花成为首个销量超过1000万吨的中国啤酒企业，2013年雪花品牌以 1062万吨的销量，成为中国首个销量超千万吨的啤酒品牌。", 
					"http://static.hutiao.me/snow/sy_images/xhzg.jpg",
					"http://mp.weixin.qq.com/s?__biz=MjM5NDA5NDUzMQ==&mid=202329344&idx=1&sn=bd47a9ef1627f068b2b195c41575f4b2#rd");
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V1002_PINPAI_HUBEI")) {
			// 品牌-雪花湖北
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("雪花湖北", 
					"雪花啤酒自2004年扎根湖北，十年间总投资超过25亿元，下设武汉、黄石、天门、宜昌4家工厂，年产能逾120万千升，是目前湖北省最大的啤酒企业。", 
					"http://static.hutiao.me/snow/sy_images/xhhb.jpg",
					"http://static.hutiao.me/snow/xhpp/2xhhb/xhhb.html");
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V1003_PINPAI_CHANPIN")) {
			// 品牌-产品
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("雪花产品", 
					"雪花超高档脸谱系列，高档黑啤、晶尊、无醇、纯生系列，及银装、勇闯天涯、原汁麦、清纯、新动等诸多品种，均深受湖北消费者喜爱。", 
					"http://static.hutiao.me/snow/sy_images/xhcp.jpg",
					"http://static.hutiao.me/snow/xhpp/3xhcp/mulu.html");
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V1004_PINPAI_MORE")) {
			// 品牌-了解更多
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("华润雪花官网", 
					"更多了解，详情请进雪花官网​。​", 
					"http://static.hutiao.me/snow/sy_images/xhgw.jpg",
					"http://static.hutiao.me/snow/xhpp/4ljgd/ljgd.html");
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V2001_HUODONG_WSSYS")) {
			// 活动-我是摄影师
			
//			StringBuffer buffer = new StringBuffer();  
//		    buffer.append("感谢您关注【雪花妹】，我们等您很久了！").append("\n\n");
//		    buffer.append("雪花湖北“我是摄影师”微信建筑摄影活动火热启动啦！拍出你喜爱的建筑，就有丰富奖品等你来拿，机会属于每一个人！").append("\n\n");
//		    buffer.append("第一步：在微信对话框中发送单幅作品").append("\n");
//		    buffer.append("第二步：以“标题#图片说明”的格式发送文字信息即可参赛 点击查看示例").append("\n\n");
//		    buffer.append("作品要求、奖项设置等征稿内容请：点击查看").append("\n");
//			
//			sendMsg = new WxSendTextMsg(sendMsg, buffer.toString());
//			this.result = WeiXinTools.getSendXmlStr(sendMsg);
			
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("活动介绍、如何参与，奖品展示", 
					"", 
					"http://static.hutiao.me/snow/hdzq/4wssys/images/01.jpg",
					"http://static.hutiao.me/snow/hdzq/4wssys/1sys.html");
			sendNewsMsg.addItem("查看他人作品", 
					"", 
					"http://static.hutiao.me/snow/hdzq/4wssys/images/02.jpg",
					ConfigInfo.hdPhotoFlowUrl+"?openId="+clickEvent.getFromUser()+"&tempid="+Math.random());
			sendNewsMsg.addItem("历史获奖作品展示", 
					"", 
					"http://static.hutiao.me/snow/hdzq/4wssys/images/03.jpg",
					ConfigInfo.hdPhotoAlbumUrl+"?openId="+clickEvent.getFromUser()+"&tempid="+Math.random());
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
			
		}  else if (clickEvent.getEventKey().equals("V2002_HUODONG_YONGCHUANG")) {
			// 活动-勇闯天涯
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("2014年勇闯天涯 挑战未登峰 湖北赛区报名结束", 
					"", 
					"http://static.hutiao.me/snow/huodong/ycty/card0.jpg",
					"http://static.hutiao.me/snow/huodong/ycty/jz.jpg");
			sendNewsMsg.addItem("勇者无畏·说出勇闯的故事", 
					"", 
					"http://static.hutiao.me/snow/huodong/ycty/card1.jpg",
					"http://static.hutiao.me/snow/huodong/ycty/photo/show.html");
			sendNewsMsg.addItem("勇闯攻略·2005-2013", 
					"", 
					"http://static.hutiao.me/snow/huodong/ycty/card3/card.jpg",
					"http://static.hutiao.me/snow/huodong/ycty/gl/index.html");
			
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V2002_HUODONG_GUOPI")) {
			
			// 活动-果啤，全城寻你
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("【参与得大礼】雪花果啤出动！寻你，巡礼！", 
					"", 
					"http://static.hutiao.me/snow/huodong/guopi/1.jpg",
					"http://static.hutiao.me/snow/huodong/guopi/guopi_nanmo.html");
			sendNewsMsg.addItem("【雪花湖北制造】果啤女王养成记", 
					"", 
					"http://static.hutiao.me/snow/huodong/guopi/2.jpg",
					"http://static.hutiao.me/snow/huodong/guopi/guopi_nvwang.html");
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
			
		} else if (clickEvent.getEventKey().equals("V2001_HUODONG_GUJIAN")) {
			// 活动-古建
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			sendNewsMsg.addItem("雪花和你一起走近荆楚古建筑",
					"", 
					"http://static.hutiao.me/snow/hdzq/2zjjcgjz/images/01.jpg",
					"http://static.hutiao.me/snow/hdzq/2zjjcgjz/1jc.html");
			sendNewsMsg.addItem("【荆楚古建筑•武当山】", 
					"", 
					"http://static.hutiao.me/snow/hdzq/2zjjcgjz/images/02.jpg",
					"http://static.hutiao.me/snow/hdzq/2zjjcgjz/2jc.html");
			sendNewsMsg.addItem("【荆楚古建筑•明显陵】", 
					"", 
					"http://static.hutiao.me/snow/hdzq/2zjjcgjz/images/03.jpg",
					"http://static.hutiao.me/snow/hdzq/2zjjcgjz/3jc.html");
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V3001_SNOWMM_RANK")) {
			// 雪花妹HOT排名
			
			List<SnowMM> mmList = this.mmService.getMMList();
			
			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
			
			String openId = clickEvent.getFromUser();
			System.out.println("-------------------------------- openId="+openId);
			logger.error("-------------------------------- openId="+openId);
			
			sendNewsMsg.addItem(mmList.get(0).getNickname(), 
					mmList.get(0).getIntroduce(), 
					mmList.get(0).getPhotoUrlBig(),
					ConfigInfo.snowmmDetailUrl+"?mmid="+mmList.get(0).getMmid()+"&visitorId="+openId);
			
			for (int i=1; i<3; i++) {
				sendNewsMsg.addItem(mmList.get(i).getNickname(), 
						mmList.get(i).getIntroduce(), 
						mmList.get(i).getPhotoUrl(),
						ConfigInfo.snowmmDetailUrl+"?mmid="+mmList.get(i).getMmid()+"&visitorId="+openId);
			}
			
			
			sendNewsMsg.addItem("查看全部排名", "", "", ConfigInfo.snowmmListUrl+"?visitorId="+openId);
			
			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V3002_SNOWMM_NEARBY")) {
			// 附近的雪花妹
			
			String openId = clickEvent.getFromUser();
			MongoUtil.removeNearbyMMSession(openId);
			MongoUtil.saveNearbyMMSession(openId);
			
			sendMsg = new WxSendTextMsg(sendMsg, "请先上传您的当前位置，我们才能帮您寻找最近的雪花妹哦～。");
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
			return SUCCESS;
			
//			UserLocation uloca = MongoUtil.findUserLocal(clickEvent.getFromUser());
//			
//			if (uloca == null) {
//				sendMsg = new WxSendTextMsg(sendMsg, "未收到您的位置信息，请您稍后再试...");
//				this.result = WeiXinTools.getSendXmlStr(sendMsg);
//				return SUCCESS;
//			}
//			
//			logger.info("uloca.latitude=" + uloca.getLatitude());
//			logger.info("uloca.longitude=" + uloca.getLongitude());
//			logger.info("uloca.precision=" + uloca.getPrecision());
//			
//			List<SnowMM> mmList = this.mmService.nearbyMM(uloca);
//			
//			if (mmList == null || mmList.size() ==0) {
//				sendMsg = new WxSendTextMsg(sendMsg, "雪花妹都不在线，请您稍后再试...");
//				this.result = WeiXinTools.getSendXmlStr(sendMsg);
//				return SUCCESS;
//			}
//			
//			String openId = clickEvent.getFromUser();
//			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
//			DecimalFormat df1 = new DecimalFormat("0.00");
//			
//			for (int i=0; i<mmList.size(); i++) {
//				
//				if (i==0) {
//					sendNewsMsg.addItem(mmList.get(i).getNickname()+"(距离"+df1.format(mmList.get(i).getDistance())+"KM)", 
//							mmList.get(i).getIntroduce(), 
//							mmList.get(i).getPhotoUrlBig(),
//							ConfigInfo.snowmmDetailUrl+"?mmid="+mmList.get(i).getMmid()+"&visitorId="+openId);
//					continue;
//				}
//				
//				sendNewsMsg.addItem(mmList.get(i).getNickname()+"(距离"+df1.format(mmList.get(i).getDistance())+"KM)", 
//						mmList.get(i).getIntroduce(), 
//						mmList.get(i).getPhotoUrl(),
//						ConfigInfo.snowmmDetailUrl+"?mmid="+mmList.get(i).getMmid()+"&visitorId="+openId);
//				
//				if (i==5) {
//					break;
//				}
//			}
//			
//			sendNewsMsg.addItem("查看所有MM", "", "", ConfigInfo.snowmmListUrl+"?visitorId="+openId);
//			
//			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
			
		} else if (clickEvent.getEventKey().equals("V3003_SNOWMM_CHART")) {
			// 雪花妹 - 聊天
			String openId = clickEvent.getFromUser();
			String redirectUrl = ConfigInfo.snowmmTalkUrl + "?visitorId="+openId;
			
			StringBuffer buffer = new StringBuffer();
			buffer.append("解答您的疑问，随便聊两句。。。").append("\n\n");
			buffer.append("<a href=\""+redirectUrl+"\">开始聊天>></a>").append("\n");
			
			sendMsg = new WxSendTextMsg(sendMsg, "好的，那就聊聊吧，请点击菜单左边的小键盘切换到输入模式发我消息，告诉我你想了解的");
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
		} else if (clickEvent.getEventKey().equals("V3001_XUEHUAMEI_SINGER")) {
			// 雪花妹 - OLD
			sendMsg = new WxSendTextMsg(sendMsg, "正在建设中，敬请期待...");
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
		}
		
		return SUCCESS;
	}
}
